package com.ali.config;

import com.ali.common.ControllerUri;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@WebFilter(urlPatterns = {"/*"}, filterName = "JWTFilter")
public class JWTFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
        log.info("JWTFilter.init.filterConfig：" + filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("JWTFilter.doFilter.servletRequest：{}, JWTFilter.doFilter.servletResponse：{}, JWTFilter.doFilter.filterChain：{}", servletRequest, servletResponse, filterChain);

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String uri = httpServletRequest.getRequestURI();
        log.info("uri：" + uri);
        String token = httpServletRequest.getHeader("token");
        log.info("token：" + token);

        checkToken(uri, token);

        filterChain.doFilter(servletRequest, servletResponse);
    }

    /**
     * 校验token
     */
    private void checkToken(String uri, String token) {
        if (ControllerUri.SKIP_CHECK_TOKEN.contains(uri)) {
            return;
        }

        try{
            JWTUtil.tokenVerify(token);
        }catch (Exception e){
            throw new RuntimeException("token校验失败");
        }
    }

    @Override
    public void destroy() {
        log.info("destroy");
    }
}
